<?php

namespace backend\modules\wechat\controllers;

use backend\controllers\AdminController;
use common\models\wechat\WechatAccounts;
use common\models\wechat\WechatFansGroups;
use common\models\wechat\WechatReplyKeyword;
use Yii;
use common\models\wechat\WechatMenus;
use backend\modules\wechat\models\WechatMenusSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MenusController implements the CRUD actions for WechatMenus model.
 */
class MenusController extends AdminController
{
    public $enableCsrfValidation = false;
    /**
     * @inheritdoc
     */
//    public function behaviors()
//    {
//        return [
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'delete' => ['POST'],
//                ],
//            ],
//        ];
//    }

    /**
     * Lists all WechatMenus models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new WechatMenusSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single WechatMenus model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new WechatMenus model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new WechatMenus();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $_W['page']['title'] = '菜单设计器 - 自定义菜单 - 高级功能';
            $id = Yii::$app->request->get('id');
            $params = [];
            $menu = [];
            if($id > 0) {
                $menu = (new Query())->select('*')->from(WechatMenus::tableName())->where(['id'=>$id])->all();
                if(!empty($menu)) {
                    $menu['data'] = unserialize(base64_decode($menu['data']));
                    if(!empty($menu['data'])) {
                        if(!empty($menu['data']['matchrule']['province'])) {
                            $menu['data']['matchrule']['province'] .= '省';
                        }
                        if(!empty($menu['data']['matchrule']['city'])) {
                            $menu['data']['matchrule']['city'] .= '市';
                        }
                        $params = $menu['data'];
                        $params['title'] = $menu['title'];
                        $params['type'] = $menu['type'];
                        $params['sex'] = $menu['sex'];
                        $params['client_platform_type'] = $menu['client_platform_type'];
                        $params['group_id'] = $menu['group_id'];
                    }
                }
            }


            $groups = WechatFansGroups::findOne(['wid'=>1])? WechatFansGroups::findOne(['wid'=>1])->getFansGroups():(new WechatFansGroups())->getFansGroups();
            if(empty($groups)) {
                $this->dialog('获取粉丝分组失败');
            }else{
                $groups = $groups['tags'];
            }
            $hasmenu = (new Query())->select('id')->from(['menu'=>WechatMenus::tableName()])->where('wid=:wid',[
                ':wid' => WechatAccounts::WID
            ])->one();

            return $this->render('create', [
                'type' => empty($hasmenu)?1:3,
                'id' => $id,
                'params' => $params,
                'menu' => $menu,
                'groups' => $groups,
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing WechatMenus model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $_W['page']['title'] = '菜单设计器 - 自定义菜单 - 高级功能';
        $type = Yii::$app->request->get('type');
        $params = [];
        if($id > 0) {
            $menu = (new Query())->select('*')->from(WechatMenus::tableName())->where('id=:id',[':id'=>$id])->one();
            if(!empty($menu)) {
                if(!empty($menu['data'])) {
                    $menu['data'] = unserialize(base64_decode($menu['data']));
                    if(!empty($menu['data']['matchrule']['province'])) {
                        $menu['data']['matchrule']['province'] .= '省';
                    }
                    if(!empty($menu['data']['matchrule']['city'])) {
                        $menu['data']['matchrule']['city'] .= '市';
                    }
                    $params = $menu['data'];
                    $params['title'] = $menu['title'];
                    $params['type'] = $menu['type'];
                    $params['sex'] = $menu['sex'];
                    $params['client_platform_type'] = $menu['client_platform_type'];
                    $params['group_id'] = $menu['group_id'];
                }
            }
            foreach ($params['button'] as $key => $row){
                if(!array_key_exists('sub_button',$row)){
                    $params['button'][$key]['sub_button'] = [];
                }
            }
        }


        $groups = WechatFansGroups::findOne(['wid'=>1])? WechatFansGroups::findOne(['wid'=>1])->getFansGroups():(new WechatFansGroups())->getFansGroups();
        if(empty($groups)) {
            $this->dialog('获取粉丝分组失败');
        }else{
            $groups = $groups['tags'];
        }
        return $this->render('update',[
            'type' => $type,
            'id' => $id,
            'params' => $params,
            'menu' => $menu,
            'groups' => $groups,
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing WechatMenus model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete()
    {
        $id = Yii::$app->request->post('id');
        $type = Yii::$app->request->get('type');
        $model = $this->findModel($id);
        if($model->menuid !=0){
            //删除微信端菜单
            $res = Yii::$app->wechat->menu->destroy($model->menuid);
            if($res->errcode == 0){
                $model->delete();
            }
            return \GuzzleHttp\json_encode(['status'=>0,'msg'=>'删除成功']);
            //return $this->dialog('删除成功','success','index');
        }
        if($model->id){
            $model->delete();
        }
        return \GuzzleHttp\json_encode(['status'=>0,'msg'=>'删除成功']);
//        return $this->redirect(['index']);
    }

    /**
     * Finds the WechatMenus model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return WechatMenus the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = WechatMenus::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @return string
     * 保存菜单
     */
    public function actionSave()
    {
        $post = Yii::$app->request->getRawBody();
        if($post){
            $post = json_decode($post,true);
        }
        $post = $post['group'];
        $menu = array();
        if(!empty($post['button'])) {
            foreach($post['button'] as &$button) {
                $temp = array();
                $temp['name'] = preg_replace_callback('/\:\:([0-9a-zA-Z_-]+)\:\:/', create_function('$matches', 'return utf8_bytes(hexdec($matches[1]));'), $button['name']);
                $temp['name'] = $temp['name'];
                if (empty($button['sub_button'])) {
                    $temp['type'] = $button['type'];
                    if($button['type'] == 'view') {
                        $temp['url'] = $button['url'];
                    } elseif ($button['type'] == 'media_id' || $button['type'] == 'view_limited') {
                        $temp['media_id'] = $button['media_id'];
                    } else {
                        $temp['key'] = $button['key'];
                    }
                } else {
                    foreach($button['sub_button'] as &$subbutton) {
                        $sub_temp = array();
                        $sub_temp['name'] = preg_replace_callback('/\:\:([0-9a-zA-Z_-]+)\:\:/', create_function('$matches', 'return utf8_bytes(hexdec($matches[1]));'), $subbutton['name']);
                        $sub_temp['name'] = $sub_temp['name'];
                        $sub_temp['type'] = $subbutton['type'];
                        if($subbutton['type'] == 'view') {
                            $sub_temp['url'] = $subbutton['url'];
                        } elseif ($subbutton['type'] == 'media_id' || $subbutton['type'] == 'view_limited') {
                            $sub_temp['media_id'] = $subbutton['media_id'];
                        } else {
                            $sub_temp['key'] = $subbutton['key'];
                        }
                        $temp['sub_button'][] = $sub_temp;
                    }
                }
                $menu['button'][] = $temp;
            }
        }

        $matchrule = [];

        $area = '';
        if($post['type'] == 3 && !empty($post['matchrule'])) {
            if(isset($post['sex']) && $post['sex'] > 0) {
                $matchrule['sex'] = $post['sex'];
            }
            if(isset($post['group_id']) && $post['group_id'] != -1) {
                $matchrule['tag_id'] = $post['group_id'];
            }
            if(isset($post['client_platform_type']) && $post['client_platform_type'] > 0) {
                $matchrule['client_platform_type'] = $post['client_platform_type'];
            }

            if(isset($post['province']) && !empty($post['province'])) {
                $matchrule['country'] = '中国';
                $area .= isset($matchrule['country'])?trim($matchrule['country']):'';
                $matchrule['province'] = rtrim($post['province'],'省');
                $area .= '-'.isset($matchrule['province'])?trim($matchrule['province']):'';
                if(!empty($post['city'])) {
                    $matchrule['city'] = rtrim($post['city'],'市');
                    $area .= '-'.isset($matchrule['city'])?trim($matchrule['city']):'';
                }
            }
        }


        if(empty($matchrule)){
            $result = \Yii::$app->wechat->menu->add($menu['button']);
        }else{
            $result = Yii::$app->wechat->menu->add($menu['button'],$matchrule);
        }

        $insert = array(
            'wid' => WechatAccounts::WID,
            'menuid' => $result->menuid?$result->menuid:0,
            'title' => $post['title'],
            'type' => $post['type'],
            'sex' => isset($matchrule['sex'])?intval($matchrule['sex']):0,
            'group_id' => isset($matchrule['tag_id']) ? $matchrule['tag_id'] : -1,
            'client_platform_type' => array_key_exists('client_platform_type',$matchrule)?intval($matchrule['client_platform_type']):0,
            'area' => $area,
            'data' => base64_encode(serialize($menu)),
            'status' => 1,
            'createtime' => time(),
        );
        if($post['type'] == 1) {
            $history = (new Query())->select('*')->from(WechatMenus::tableName())->where(['wid'=>WechatAccounts::WID,'type'=>2])->one();
            if(empty($history)) {
                $data = $insert;
                $data['type'] = 2;
                $data['status'] = 0;
                Yii::$app->db->createCommand()->insert(WechatMenus::tableName(),$data)->execute();
            } else {
                $data = $insert;
                $data['type'] = 2;
                $data['status'] = 0;
                Yii::$app->db->createCommand()->update(WechatMenus::tableName(),$data,'wid=:wid and type=:type',[':wid'=>WechatAccounts::WID,':type'=>2])->execute();
            }

            $default = (new Query())->select('*')->from(WechatMenus::tableName())->where(['wid'=>WechatAccounts::WID,'type'=>1])->one();
            if(!empty($default)) {
                $res = Yii::$app->db->createCommand()->update(WechatMenus::tableName(),$insert,'wid=:wid and type=:type',[':wid'=>WechatAccounts::WID,':type'=>1])->execute();
                return $res?json_encode(['message'=>'设置成功','errno'=>0]):json_encode(['message'=>'设置失败','errno'=>1]);
            }
        }
        $res = Yii::$app->db->createCommand()->insert(WechatMenus::tableName(),$insert)->execute();
        return $res?json_encode(['message'=>'设置成功','errno'=>0]):json_encode(['message'=>'设置失败','errno'=>1]);
    }


    /**
     * 搜索关键字
     */
    public function actionSearchKwd()
    {
        $key_word = trim(Yii::$app->request->post('key_word'));
        $query = (new Query())->select('content')->from(['kwd'=>WechatReplyKeyword::tableName()])->where('status=1');

        if(!empty($key_word)) {
            $query->andWhere(['like','content',$key_word])
                ->all();
        }
        $data = $query->all();


        $exit_da = [];
        if(!empty($data)) {
            foreach($data as $da) {
                $exit_da[] = $da['content'];
            }
        }
        exit(json_encode($exit_da));
    }


    public function actionCeshi()
    {
//        $res = \Yii::$app->wechat->menu->destroy(417816825);
//        var_dump($res);
//        exit;

//        \Yii::$app->wechat->menu->destroy();
//         $aa = \Yii::$app->wechat->menu->all();
//         VarDumper::dump($aa);exit;
        $menus = \Yii::$app->wechat->menu->test('ocIHlvuYEL42sF_3ktKeMftWemlw');
        VarDumper::dump($menus);exit;
    }
}
